package com.xuecheng.manage_media.service;

import com.xuecheng.framework.domain.media.MediaFile;
import com.xuecheng.framework.domain.media.request.QueryMediaFileRequest;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.manage_media.dao.MediaFileRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;


/**
 * 标题：
 * 作者：何处是归程
 * 时间：2020/3/10 - 16:07
 */
@Service
public class MediaFileService {
	@Autowired
	MediaFileRepository mediaFileRepository;

	// 我的媒资文件查询列表
	public QueryResponseResult<MediaFile> findList(int page, int size, QueryMediaFileRequest queryMediaFileRequest) {
		//分页查询对象
		if (page <= 0) {
			page = 1;
		}
		page = page - 1;
		if (size <= 0) {
			size = 10;
		}
		if (queryMediaFileRequest == null) {
			queryMediaFileRequest = new QueryMediaFileRequest();
		}

		//条件值对象
		MediaFile mediaFile = new MediaFile();
		if (!StringUtils.isEmpty(queryMediaFileRequest.getTag())) {
			mediaFile.setTag(queryMediaFileRequest.getTag());
		}
		if (!StringUtils.isEmpty(queryMediaFileRequest.getFileOriginalName())) {
			mediaFile.setFileOriginalName(queryMediaFileRequest.getFileOriginalName());
		}
		if (!StringUtils.isEmpty(queryMediaFileRequest.getProcessStatus())) {
			mediaFile.setProcessStatus(queryMediaFileRequest.getProcessStatus());
		}
		//条件匹配器
		ExampleMatcher exampleMatcher = ExampleMatcher.matching()
				.withMatcher("tag", ExampleMatcher.GenericPropertyMatchers.contains())
				.withMatcher("fileOriginalName", ExampleMatcher.GenericPropertyMatchers.contains());
		//定义example条件对象
		Example<MediaFile> example = Example.of(mediaFile, exampleMatcher);
		Pageable pageable = new PageRequest(page, size);
		//分页查询
		Page<MediaFile> all = mediaFileRepository.findAll(example, pageable);
		//总记录数
		long total = all.getTotalElements();
		//数据列表
		List<MediaFile> content = all.getContent();
		//返回的数据集
		QueryResult<MediaFile> queryResult = new QueryResult<>();
		queryResult.setList(content);
		queryResult.setTotal(total);

		//返回结果
		QueryResponseResult queryResponseResult = new QueryResponseResult(CommonCode.SUCCESS, queryResult);
		return queryResponseResult;
	}
}
